<template>
  <div>
    <el-form :inline="true" :model="searchClient" label-width="110px" ref="searchForm">
      <el-form-item prop="code">
        <el-input v-model.trim="searchClient.code" auto-complete="off" placeholder="客户代码"></el-input>
      </el-form-item>
      <el-form-item prop="province" v-if="searchClient.roleType === '1'">
        <v-distpicker @selected="onSearchSelected" :provinceOut="searchClient.province" only-province>
        </v-distpicker>
      </el-form-item>
      <el-form-item prop="city" v-if="searchClient.roleType === '2' && searchClient.preOfficeType === '0'">
        <el-select v-model="searchClient.city" clearable placeholder="请选择城市">
          <el-option
            v-for="item in searchCityList"
            :key="item.code"
            :value="item.code"
            :label="item.name"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="clientType">
        <el-select v-model="searchClient.clientType" clearable placeholder="客户类型">
          <el-option
            v-for="item in customerTypeOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="company">
        <el-input v-model.trim="searchClient.company" placeholder="客户公司名称"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="searchData">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleAdd">新增</el-button>
      </el-form-item>
      <el-form-item>
        <el-dropdown @command="handleCommand">
          <el-button type="primary">导入<i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <a href="/static/客户导入模板.xlsx" download="客户导入模板.xlsx"
               style="color:#5a5e66;text-decoration: none ">
              <el-dropdown-item command="handleDownload">模板下载
              </el-dropdown-item>
            </a>
            <el-dropdown-item command="handleImport">数据导入</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="excelExport">数据导出</el-button>
      </el-form-item>
    </el-form>

    <custom-table
      :columns='columns'
      :data="clientList"
      :tableLoadingFlag="tableLoadingFlag"
      :operationColumn="operationColumn"
      :pagination="pagination">
    </custom-table>

    <!-- 客户模板导入模态框 -->
    <el-dialog title="模板导入" :visible.sync="uploadVisible"
               :close-on-click-modal="false" :before-close="uploadCancel">
      <div>
        <el-form label-width="80px" ref="uploadForm" :inline="true">
          <el-form-item style="padding-left: 120px">
            <el-upload
              class="upload-demo"
              :action="uploadUrl"
              :headers="myHeaders"
              name="file"
              :on-error="uploadError"
              :on-success="uploadSuccess"
              :before-upload="beforeAvatarUpload"
              multiple
              drag
              :limit="1"
              :file-list="fileList">
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em><br/>只能上传xlsx文件，且不超过10M</div>
            </el-upload>
          </el-form-item>
          <!--显示导入中错误的数据-->
          <div style="height: 200px;overflow-y: auto" v-if="hideTable">
            <custom-table
              :data="wrongDataList"
              :columns="detailColumns">
            </custom-table>
          </div>
        </el-form>
      </div>
      <div slot="footer">
        <el-button type="primary" @click="uploadCancel()">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="dialogType ==='add'? '新增客户':'修改客户信息'" :visible.sync="dialogVisible"
               :close-on-click-modal="false">
      <el-form :rules="clientRules" :model="clientDto" label-width="110px" ref="clientForm">
        <el-form-item label="客户代码" prop="code">
          <el-input v-model="clientDto.code" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="客户类型" prop="customerType">
          <el-select v-model="clientDto.customerType" placeholder="请选择客户类型" @change="onCustomerTypeChange">
            <el-option
              v-for="item in customerTypeOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="公司名称" prop="company">
          <el-input v-model="clientDto.company" auto-complete="off" :disabled="disabled"></el-input>
        </el-form-item>
        <el-form-item label="客户所在地区">
          <el-row>
            <el-col :span="6">
              <el-select v-model="clientDto.provinceCode" clearable placeholder="请选择省份" @click="getAllProvince()"
                         @change="getAllCity()" :disabled="this.roleType === '2'">
                <el-option
                  v-for="item in allProvince"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code">
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="6" prop="cityRule">
              <el-select v-model="clientDto.cityCode" clearable placeholder="请选择城市" @click="getAllCity()"
                         @change="getArea()" :disabled="this.preOfficeType === '1'">
                <el-option
                  v-for="item in allCity"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code">
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="6" prop="areaRule">
              <el-select v-model="clientDto.areaCode" clearable placeholder="请选择地区" @click="getArea()">
                <el-option
                  v-for="item in allArea"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code">
                </el-option>
              </el-select>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="clientDto.address" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="联系人" prop="contact">
          <el-input v-model="clientDto.contact" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="tel">
          <el-input v-model="clientDto.tel" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="物流联系人" prop="logisticsContact">
          <el-input v-model="clientDto.logisticsContact" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="物流联系电话" prop="logisticsTel">
          <el-input v-model="clientDto.logisticsTel" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import CustomTable from '@/components/table/CustomTable'
  import {
    apiGetClientList,
    apiGetClientById,
    apiDelClient,
    apiAddClient,
    apiUpdClient,
    apiExport
  } from '@/api/basic/info/client'
  import {apiCustomReadExcel} from '@/api/excel/excelRead'
  import Distpicker from '@/components/distpicker/index'
  import store from '@/store'
  import {baseInfo} from '@/utils/fetch'
  import {getRoleType, getProvinceCode, getOfficeType, getCityCode} from '@/utils/token'
  import {
    apiGetCity,
    apiGetArea
  } from '@/api/dictionary'
  import {downloadExcel} from "../../../utils";

  export default {
    name: 'client',
    components: {
      CustomTable,
      Distpicker
    },
    created () {
      this.getAllProvince()
      this.roleType = getRoleType()
      this.preOfficeType = getOfficeType()
      if (this.roleType === '2' && this.preOfficeType === '0') {
        let listQuery = {
          province: getProvinceCode()
        }
        apiGetCity(listQuery).then(rsp => {
          this.searchCityList = rsp.data
        })
      }
      let listQuery = {
        pageNumber: this.pagination.currentPage,
        pageSize: this.pagination.pageSize
      }
      this.getClientList(listQuery)
    },
    data () {
      return {
        uploadUrl: baseInfo() + '/api/v1/upload',
        myHeaders: {'access_token': store.getters.token},
        // 上传文件显示
        fileList: [],
        // 文件上传路径
        importFileUrl: baseInfo() + '/api/v1/upload',
        // 文件上传参数
        upLoadData: {},
        searchClient: {
          code: '',
          company: '',
          province: '',
          city: '',
          clientType: undefined,
          roleType: getRoleType(),
          preOfficeType: getOfficeType()
        },
        uploadVisible: false,
        hideTable: false,
        dialogVisible: false,                              // 客户档案模态框相关数据
        customerTypeOptions: this.getCustomerTypeList(),
        disabled: false,
        dialogType: '',
        filePath: '',
        listQuery: {
          code: undefined,
          provinceCode: undefined,
          customerType: undefined,
          company: undefined,
          cityCode: undefined
        },
        clientDto: {
          code: '',
          customerType: undefined,
          company: '',
          contact: '',
          tel: '',
          logisticsContact: '',
          logisticsTel: '',
          provinceCode: '',
          cityCode: '',
          areaCode: '',
          province: '',
          city: '',
          area: '',
          address: ''
        },
        clientRules: {
          code: [
            {required: true, message: '请输入客户代码', trigger: 'blur'},
            {min: 12, max: 12, message: '长度12个字符，省市各2位，客户类型2位，后6位自己命名,如：JSWX01YD0224', trigger: 'blur'}
          ],
          company: [
            {required: true, message: '请输入客户公司名称', trigger: 'blur'},
            {max: 50, message: '长度不得超过50字符', trigger: 'blur'}
          ],
          customerType: [
            {type: 'number', required: true, message: '请选择客户类型', trigger: 'change'}
          ],

          address: [
            {required: true, message: '请输入详细地址', trigger: 'blur'},
            {max: 255, message: '长度不超过 255 个字符', trigger: 'blur'}
          ],
          contact: [
            {required: true, message: '请输入联系人', trigger: 'blur'},
            {max: 20, message: '长度不得超过20字符', trigger: 'blur'}
          ],
          tel: [
            {required: true, message: '请输入联系电话', trigger: 'blur'}
          ],
          logisticsTel: [
            {required: true, message: '请输入物流联系电话', trigger: 'blur'}
          ],
          logisticsContact: [
            {max: 20, message: '长度不得超过20字符', trigger: 'blur'}
          ]
        },
        tableLoadingFlag: false,                       // 客户档案一览相关数据
        columns: [
          {label: 'ID', name: 'id', width: '80', align: 'center'},
          {label: '客户代码', name: 'code', width: '150', align: 'center'},
          {label: '省份', name: 'province', width: '150', align: 'center'},
          {label: '客户类型', name: 'customerType', width: '120', align: 'center'},
          {label: '客户公司名称', name: 'company', align: 'center'},
          {label: '联系人', name: 'contact', align: 'center'}
        ],
        detailColumns: [
          {label: '错误行号', name: 'wrongRowNO', width: '77', height: '40', align: 'center'},
          {label: '错误原因', name: 'reason', width: '120', height: '40', align: 'center'},
          {label: '客户代码', name: 'code', width: '80', height: '40', align: 'center'},
          {label: '客户类型', name: 'customerType', width: '80', height: '40', align: 'center'},
          {label: '公司名称', name: 'company', width: '80', height: '40', align: 'center'},
          {label: '联系人', name: 'contact', width: '80', height: '40', align: 'center'},
          {label: '联系电话', name: 'tel', width: '80', height: '40', align: 'center'},
          {label: '物流联系人', name: 'logisticsContact', width: '80', height: '40', align: 'center'},
          {label: '物流联系电话', name: 'logisticsTel', width: '80', height: '40', align: 'center'},
          {label: '省份', name: 'province', width: '80', height: '40', align: 'center'},
          {label: '城市', name: 'city', width: '80', height: '40', align: 'center'},
          {label: '地区', name: 'area', width: '80', height: '40', align: 'center'},
          {label: '详细地址', name: 'address', width: '80', height: '40', align: 'center'}
        ],
        operationColumn: {
          width: '100',
          operations: [
            {name: '编辑', callback: this.handleEdit},
            {name: '删除', callback: this.handleDel}
          ]
        },
        clientList: [],
        wrongDataList: [],
        pagination: this.getData(this.getClientList),
        roleType: getRoleType(),
        allProvince: [],
        allCity: [],
        allArea: [],
        searchCityList: []
      }
    },
    methods: {
      excelExport () {
        let paramsPost = {
          customerType: this.searchClient.clientType,
          code: this.searchClient.code,
          company: this.searchClient.company,
          provinceCode: this.searchClient.province,
          cityCode: this.searchClient.city
        }
        if (this.roleType === '2' && this.preOfficeType === '0') {
          paramsPost.provinceCode = getProvinceCode()
        } else if (this.roleType === '2' && this.preOfficeType === '1') {
          paramsPost.cityCode = getCityCode()
        }
        apiExport(paramsPost).then(response => {
          downloadExcel(response.data, '自有售后客户信息导出表')
        }).catch(err => {
          console.log(err)
        })
      },
      // 上传成功后的回调
      uploadSuccess (response, file, fileList) {
        this.$message({
          showClose: true,
          message: '上传文件成功！'
        })
        let filePath = response.data
        this.excelRead(filePath)
      },
      // 上传错误
      uploadError (err, file, fileList) {
        this.$message({
          showClose: true,
          message: '上传失败，请重试！'
        })
      },
      // 上传前对文件的大小的判断
      beforeAvatarUpload (file) {
        const extension = file.name.split('.')[1] === 'xlsx'
        const isLt2M = file.size / 1024 / 1024 < 10
        if (!extension) {
          this.$message({
            showClose: true,
            message: '上传模板只能是 xlsx 格式!'
          })
        }
        if (!isLt2M) {
          this.$message({
            showClose: true,
            message: '上传模板大小不能超过 10MB!'
          })
        }

        return extension && isLt2M
      },
      excelRead (filePath) {
        apiCustomReadExcel(filePath).then(response => {
          if (response.data) {
            this.wrongDataList = response.data
            this.hideTable = true
          } else {
            this.$message({
              showClose: true,
              message: '导入执行中，请稍后',
              type: 'success'
            })
            this.hideTable = false
          }
          this.fileList = []
          this.getClientList({
            pageNumber: this.pagination.currentPage,
            pageSize: this.pagination.pageSize
          })
        })
      },
      handleCommand (command) {
        if (command === 'handleImport') {
          this.dialogType = 'upload'
          this.uploadVisible = true
        } else if (command === 'handleDownload') {
        }
      },
      uploadCancel () {
        this.uploadVisible = false
        this.wrongDataList = []
        this.fileList = []
        this.hideTable = false
        this.$refs['uploadForm'].resetFields()
      },
      onCustomerTypeChange (val) { // 个人和装维，公司名称显示为“个人”且不可编辑
        if (val === 2 || val === 4) {
          this.clientDto.company = '个人'
          this.disabled = true
        } else {
          this.disabled = false
        }
      },
      getClientList (listQuery) {
        this.tableLoadingFlag = true
        if (listQuery.code === undefined) {
          listQuery.code = this.searchClient.code
        }
        if (listQuery.provinceCode === undefined && this.roleType === '1') {
          listQuery.provinceCode = this.searchClient.province
        }
        if (listQuery.customerType === undefined) {
          listQuery.customerType = this.searchClient.clientType
        }
        if (listQuery.company === undefined) {
          listQuery.company = this.searchClient.company
        }
        if (listQuery.cityCode === undefined && this.roleType === '2' && this.preOfficeType === '0') {
          listQuery.cityCode = this.searchClient.city
        }
        listQuery.roleType = getRoleType()
        listQuery.preOfficeType = getOfficeType()
        apiGetClientList(listQuery).then(response => {
          this.clientList = response.data
          this.pagination.totalRecords = response.totalRecords
          this.tableLoadingFlag = false
        }).catch(() => {
          this.tableLoadingFlag = false
        })
      },
      handleAdd () {
        this.dialogType = 'add'
        this.dialogVisible = true
        if (this.$refs['clientForm']) {
          this.clientDto = {
            code: '',
            customerType: undefined,
            company: '',
            contact: '',
            tel: '',
            logisticsContact: '',
            logisticsTel: '',
            provinceCode: '',
            cityCode: '',
            areaCode: '',

            province: '',
            city: '',
            area: '',
            address: ''
          }
          this.$refs['clientForm'].resetFields()
        }
        // 省办事处
        if (this.roleType === '2' && this.preOfficeType === '0') {
          this.clientDto.provinceCode = getProvinceCode()
          let listQuery = {
            province: getProvinceCode
          }
          this.getAllCity(listQuery)
        }
        // 市办事处
        if (this.roleType === '2' && this.preOfficeType === '1') {
          this.clientDto.provinceCode = getProvinceCode()
          this.clientDto.cityCode = getCityCode()
          this.getAllCity()
          this.clientDto.provinceCode = getProvinceCode()
          this.clientDto.cityCode = getCityCode()
          this.getArea()
        }
      },
      handleEdit (row) {
        apiGetClientById(row.id).then(response => {
          if (response.data.provinceCode !== undefined) {
            let cityQuery = {
              province: response.data.provinceCode
            }
            apiGetCity(cityQuery).then(rsp => {
              this.allCity = rsp.data
            })
          }
          if (response.data.cityCode !== undefined) {
            let areaQuery = {
              city: response.data.cityCode
            }
            apiGetArea(areaQuery).then(rsp => {
              this.allArea = rsp.data
            })
          }
          this.clientDto = response.data
          this.dialogType = 'edit'
          this.dialogVisible = true
        })
      },
      handleDel (row) {
        this.$confirm('确定删除该客户?', '删除客户', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          apiDelClient(row.id).then(() => {
            this.$message({
              showClose: true,
              type: 'success',
              message: '删除成功!'
            })
            this.getClientList(this.listQuery)
          })
        }).catch(() => {
        })
      },
      submit () {
        this.$refs['clientForm'].validate((valid) => {
          if (valid) {
            if (this.dialogType === 'add') {
              this.addSubmit()
            } else {
              this.updSubmit()
            }
          } else {
            return false
          }
        })
      },
      addSubmit () {
        apiAddClient(this.clientDto).then(() => {
          this.$message({
            showClose: true,
            message: '新增成功',
            type: 'success'
          })
          this.cancel()
          this.getClientList(this.listQuery)
        })
      },
      updSubmit () {
        apiUpdClient(this.clientDto).then(() => {
          this.$message({
            showClose: true,
            message: '更新成功',
            type: 'success'
          })
          this.cancel()
          this.getClientList(this.listQuery)
        })
      },
      cancel () {
        this.clientDto.province = ''
        this.clientDto.city = ''
        this.clientDto.area = ''
        this.$refs['clientForm'].resetFields()
        this.dialogVisible = false
      },
      onSearchSelected (data) {             // 省市区联动回调
        this.searchClient.province = data.province.code
      },
      searchData () {
        this.listQuery.code = this.searchClient.code
        this.listQuery.provinceCode = this.searchClient.province
        this.listQuery.customerType = this.searchClient.clientType
        this.listQuery.company = this.searchClient.company
        this.listQuery.cityCode = this.searchClient.city
        this.pagination.currentPage = 1
        this.pagination.pageSize = 10
        this.getClientList(this.listQuery)
      },
      getAllCity () {
        this.clientDto.cityCode = ''
        this.clientDto.areaCode = ''
        if (this.clientDto.provinceCode === '') {
          this.allCity = []
          this.allArea = []
        } else {
          let listQuery = {
            province: this.clientDto.provinceCode
          }
          apiGetCity(listQuery).then(response => {
            this.allCity = response.data
          })
        }
      },
      getArea () {
        this.clientDto.areaCode = ''
        if (this.clientDto.provinceCode === '' | this.clientDto.cityCode === '') {
          this.allArea = []
        } else {
          let listQuery = {
            city: this.clientDto.cityCode
          }
          apiGetArea(listQuery).then(response => {
            this.allArea = response.data
          })
        }
      },
      getAllProvince () {
        apiGetCity().then(response => {
          this.allProvince = response.data
        })
      }
    }
  }
</script>
